#!/bin/bash

host=10.xx.xx.xxx
user=xxx
pwd=xxx
port=3306
DBPATH=/evcharge/mysqlbak
OPTIONS="-h$host -u$user -p$pwd -P$port --single-transaction --triggers --log-error=${DBPATH}/backup_error.dat --opt -R -K -E"
DT=`date +%Y%m%d_%H%M`
D1=$(date +%Y\%m%d%H)

function dbbackup_old()
{
[ -d ${DBPATH}/${D1} ] || mkdir -p ${DBPATH}/${D1}
for db in  `mysql -h$host -u$user -p$pwd -P$port -s -e "show databases"|egrep -v "information_schema|performance_schema|test"`
do
	echo "$DT Start backup $db" >> ${DBPATH}/backup_log.dat
	/usr/bin/mysqldump $OPTIONS $db > ${DBPATH}/${D1}/${db}_$DT.sql
done
}

function dbbackup_action()
{
[ -d ${DBPATH}/${D1} ] || mkdir -p ${DBPATH}/${D1}
echo "$DT Start backup $1" >> ${DBPATH}/backup_log.dat
#/usr/bin/mysqldump $OPTIONS $1 > ${DBPATH}/${D1}/$1_$DT.sql
/usr/bin/mysqldump $OPTIONS $1 |gzip > ${DBPATH}/${D1}/$1_$DT.gz
}

function dbstatus()
{
/usr/bin/mysql  -h$host -u$user -p$pwd -P$port -s -e "show master status"|awk 'getline ;{print $1,$2}' > /evcharge/mysqlbak/backup_log.dat 2>&1
}

function cleanbackup()
{
find /evcharge/mysqlbak/[0-9]* -type d -mtime +7|xargs rm -rf
}

function many_process1()
{
trap "exec 999>&-;exec 999<&-;exit 0" 2
mkfifo testfifo999
exec 999<>testfifo999
rm -rf testfifo999
for((fifon=1;fifon<=3;fifon++))
do
	echo >&999
done
for db in `mysql -h$host -u$user -p$pwd -P$port -s -e "show databases"|egrep -v "information_schema|performance_schema|test"`
do
	read -u999
	{
	dbbackup_action $db
	echo >&999
	}&
done
wait
exec 999>&-
exec 999<&-
}

many_process1
cleanbackup